var express = require('express');
var router = express.Router();  
const path = require('path'); // 引入path模块处理路径

// 引入JWT模块，用于解析token
const jwt = require('jsonwebtoken');

// JWT密钥，与生成token时使用的密钥必须一致
const JWT_SECRET = process.env.JWT_SECRET || 'PLMOP';

/**
 * token解析中间件
 * 作用：对GET请求、登录接口和预检请求放行，其他请求验证token
 */
const parseToken = (req, res, next) => {
  // 1. 放行预检请求（OPTIONS）
  if (req.method === 'OPTIONS') {
    // 设置跨域允许的头部信息（根据实际需求调整）
    res.setHeader('Access-Control-Allow-Origin', req.headers.origin || '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    res.setHeader('Access-Control-Max-Age', '86400'); // 预检请求缓存时间（24小时）
    return res.status(204).end(); // 204 No Content表示成功但无内容
  }

  // 2. 对GET请求直接放行（页面、图片、静态资源等）
  if (req.method === 'GET') {
    return next();
  }

  // 3. 对登录接口特殊放行（无论什么方法）
  if (req.path === '/user/login') {
    return next();
  }

  // 4. 其他请求（POST/PUT/DELETE等）需要验证token
  try {
    const authHeader = req.headers.authorization;
    
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
      return res.status(401).json({ 
        code: 401, 
        msg: '未携带token，无权限访问' 
      });
    }
    
    const token = authHeader.split(' ')[1];
    const decoded = jwt.verify(token, JWT_SECRET);
    
    req.auth = {
      user_id: decoded.user_id,
      role_id: decoded.role_id
    };
    
    next();
  } catch (error) {
    return res.status(401).json({ 
      code: 401, 
      msg: 'token无效或已过期，请重新登录' 
    });
  }
};

// 应用token验证中间件（会自动区分请求类型）
router.use(parseToken);

// 导入并挂载所有路由
const userRoutes = require('./adminroute/SHIP/user.js');
var menu = require('./adminroute/SHIP/menu.js');
var sys = require('./adminroute/SHIP/sys.js');
var role = require('./adminroute/SHIP/role.js');
var framework = require('./adminroute/SHIP/framework.js');
var dev = require('./adminroute/SHIP/dev.js');
var operation = require('./adminroute/SHIP/operation.js');
var sales = require('./adminroute/SHIP/sales.js');
var productDelivery = require('./adminroute/SHIP/productDelivery.js');
var afterSales = require('./adminroute/SHIP/afterSales.js');
var excel = require('./adminroute/SHIP/excel.js');
var error = require('./adminroute/SHIP/error.js');
var notice = require('./adminroute/SHIP/notice.js');
var customer = require('./adminroute/SHIP/customer.js');
var station = require('./adminroute/SHIP/station.js');
var product = require('./adminroute/SHIP/product.js');
var bom = require('./adminroute/SHIP/bom.js')

router.use('/user', userRoutes);
router.use('/menu', menu);
router.use('/sys', sys);
router.use('/role', role);
router.use('/framework', framework);
router.use('/dev', dev);
router.use('/operation', operation);
router.use('/sales', sales);
router.use('/productDelivery', productDelivery);
router.use('/afterSales', afterSales);
router.use('/excel', excel);
router.use('/error', error);
router.use('/notice', notice);
router.use('/customer', customer);
router.use('/station', station);
router.use('/product', product);
router.use('/bom', bom);

// 单页应用支持（注意：路径会自动拼接上主应用中的/admin前缀）
router.get('*', (_req, res) => {
  // 根据你的静态资源实际存放位置调整路径
  res.sendFile(path.join(__dirname, '../../dist/index.html'));
});

module.exports = router;
